package com.jwm.power.util;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.swing.*;

public class getMiniAccessUtil {

    private static RestTemplate restTemplate;

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public static String getAccessToken(){

        //String APPID=App.APPID;
        //String APPSECRET=App.APP_SECRET;
        String APPID="wxb157430b96c39666";
        String APPSECRET="5a9255e5ff0c4a37afea3b09c9194cdc";
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
        System.out.println("accessTokenUrl = " + accessTokenUrl);
        ResponseEntity<String> response = restTemplate.getForEntity(accessTokenUrl, String.class);
        if(response.getStatusCode().is2xxSuccessful()) {
             Object access_token = response.getBody();
            System.out.println(access_token);
//        HttpClientUtil hru = new HttpClientUtil();
//        String access_token = hru.sendHttpGet(accessTokenUrl);
            JSONObject jsonObject = JSON.parseObject((String) access_token);
            String token = jsonObject.get("access_token").toString();//获取access_token
//        if(Tool.isEmpty(access_token)){
//            access_token="";
//        }
//        System.out.println("json:"+json.toString());
            System.out.println("access_token = " + token);
            return token;
        }
        else {
            return null;
        }
    }

    /**
     * 调用微信开放接口subscribeMessage.send发送订阅消息(固定模板的订阅消息)
     * POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
     */
    public static void sendSubscribeMessage(String toUserOpenId){
        HttpURLConnection httpConn = null;
        InputStream is = null;
        BufferedReader rd = null;
        String accessToken = null;
        String str = null;
        try
        {
            //获取token  小程序全局唯一后台接口调用凭据
            accessToken = getAccessToken();

            JSONObject xmlData = new JSONObject();
            xmlData.put("touser", toUserOpenId);//接收者（用户）的 openid
            xmlData.put("template_id", "a9Nk8CNzZVmhn5QPIDOlWp7FhbvzDqPFTHVhH9CAgJY");//所需下发的订阅模板id
            xmlData.put("page", "pages/index/index");//点击模板卡片后的跳转页面，仅限本小程序内的页面
            xmlData.put("miniprogram_state", "developer");//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
            xmlData.put("lang", "zh_CN");//进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN返回值

            /**
             * 订阅消息参数值内容限制说明
             thing.DATA:20个以内字符;可汉字、数字、字母或符号组合
             time.DATA:24小时制时间格式（支持+年月日），支持填时间段，两个时间点之间用“~”符号连接
             */

            JSONObject data = new JSONObject();
            //取餐号
            JSONObject character_string4 = new JSONObject();//character_string4必须和模板消息的字段id一致，以下同样，必须要一致，注意时间格式，详情看图二
            character_string4.put("value", "1001");
            data.put("character_string4", character_string4);
            //购买商品
            JSONObject thing5 = new JSONObject();
            thing5.put("value", "牛肉水饺");
            data.put("thing5", thing5);
            //温馨提示
            JSONObject thing11 = new JSONObject();
            thing11.put("value", "请到前台出示二维码取餐哦！");
            data.put("thing11", thing11);

            xmlData.put("data", data);//小程序模板数据


            System.out.println("发送模板消息xmlData:" + xmlData);
            URL url = new URL(
                    "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="
                            + accessToken);
            httpConn = (HttpURLConnection)url.openConnection();
            httpConn.setRequestProperty("Host", "https://api.weixin.qq.com");
            // httpConn.setRequestProperty("Content-Length", String.valueOf(xmlData.));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"UTF-8\"");
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            OutputStream out = httpConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
            osw.write(xmlData.toString());
            osw.flush();
            osw.close();
            out.close();
            is = httpConn.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            while ((str = rd.readLine()) != null)
            {
                System.out.println("返回数据：" + str);
            }
        }
        catch (Exception e)
        {
            System.out.println("发送模板消息失败.." + e.getMessage());
        }
    }

    /**
     * 调用微信开放接口subscribeMessage.send发送订阅消息    通用类
     * POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
     */
    public static void sendCommonSubscribeMessage(Map<String,Object> params,JSONObject data){
        HttpURLConnection httpConn = null;
        InputStream is = null;
        BufferedReader rd = null;
        String accessToken = null;
        String str = null;
        try
        {
            //获取token  小程序全局唯一后台接口调用凭据
            accessToken = getAccessToken();

            JSONObject xmlData = new JSONObject();
            xmlData.put("touser", params.get("touser"));//接收者（用户）的 openid
            xmlData.put("template_id", params.get("template_id"));//所需下发的订阅模板id
            xmlData.put("page", params.get("page"));//点击模板卡片后的跳转页面，仅限本小程序内的页面
            xmlData.put("miniprogram_state", params.get("miniprogram_state"));//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
            xmlData.put("lang", "zh_CN");//进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN返回值
            xmlData.put("data", data);//小程序模板数据


            System.out.println("发送模板消息xmlData:" + xmlData);
            URL url = new URL(
                    "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="
                            + accessToken);
            httpConn = (HttpURLConnection)url.openConnection();
            httpConn.setRequestProperty("Host", "https://api.weixin.qq.com");
            // httpConn.setRequestProperty("Content-Length", String.valueOf(xmlData.));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"UTF-8\"");
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            OutputStream out = httpConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
            osw.write(xmlData.toString());
            osw.flush();
            osw.close();
            out.close();
            is = httpConn.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            while ((str = rd.readLine()) != null)
            {
                System.out.println("返回数据：" + str);
            }
        }
        catch (Exception e)
        {
            System.out.println("发送模板消息失败.." + e.getMessage());
        }
    }

    public static void main(String[] args) {

        String openid = "需要接收订阅消息的openid";//需要该用户已经授权过该订阅消息才能发送
        sendSubscribeMessage(openid);//调用发送方法测试结果，数据是写死的，开发者可根据实际情况进行改写填充，真正调用只需把数据传入sendCommonSubscribeMessage方法即可

    }
}
